package com.biz.primus.ms.commodity.service.backend.keyword;

import com.biz.primus.base.exception.utils.AssertUtils;
import com.biz.primus.commodity.exception.CommodityExceptionType;
import com.biz.primus.commodity.vo.keyword.KeywordQueryVo;
import com.biz.primus.commodity.vo.keyword.KeywordVo;
import com.biz.primus.common.utils.CopyUtils;
import com.biz.primus.common.vo.SpringPageVO;
import com.biz.primus.ms.base.service.AbstractBaseService;
import com.biz.primus.ms.base.vo.SpringPageToSpringPageVO;
import com.biz.primus.ms.commodity.dao.po.Keyword;
import com.biz.primus.ms.commodity.dao.redis.keyword.KeywordRedisDao;
import com.biz.primus.ms.commodity.dao.repository.product.keyword.KeywordRepository;
import com.biz.primus.ms.commodity.dao.ro.KeywordRo;
import com.biz.primus.ms.commodity.trans.keyword.Keyword2KeywordRo;
import com.biz.primus.ms.commodity.trans.keyword.KeywordRo2KeywordVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 */
@Slf4j
@Service
public class KeywordBackendService extends AbstractBaseService {

    @Autowired
    private KeywordRepository keyWordRepository;

    @Autowired
    private KeywordRedisDao keywordRedisDao;

    public SpringPageVO<KeywordVo> findAll(KeywordQueryVo reqVo) {
        PageRequest pageRequest = reqVo.toPageRequest();
        Page<Keyword> all = keyWordRepository.findAll(pageRequest);
        return SpringPageToSpringPageVO.of(all,input-> CopyUtils.copyProperties(input,new KeywordVo()));
    }

    @Transactional
    public void saveOrUpdate(KeywordVo vo) {
        Keyword keyword = new Keyword();
        if(StringUtils.isBlank(vo.getId())){
            log.info("create keyword {}",vo);
            vo.setId(String.valueOf(idService.getNextId()));
            keyword.setId(idService.getNextId());
            CopyUtils.copyProperties(vo,keyword);
        }else {
            keyword = keyWordRepository.findOne(Long.valueOf(vo.getId()));
            AssertUtils.notNull(keyword, CommodityExceptionType.COMMON_EXCEPTION,"找不到关键字");
            CopyUtils.copyProperties(vo,keyword);
        }
        saveOrUpdateUsingPo(keyWordRepository, keywordRedisDao, keyword, new Keyword2KeywordRo());
    }

    public KeywordVo findOne(Long id) {
        return new KeywordRo2KeywordVo().apply(keywordRedisDao.findOne(id));
    }

    @Transactional
    public void delete(Long id) {
        keyWordRepository.delete(id);
        final KeywordRo keywordRo = keywordRedisDao.findOne(id);
        this.delayer.executeAfterTransactionCommit(()->{
            keywordRedisDao.delete(keywordRo);
        });
    }
}
